<?php
/**
 * This file is part of the Agora distribution. 
 * Detailed copyright and licensing information can be found
 * in the gpl-3.0.txt file which should be included in the distribution.
 * 
 * @version		$Id: 3.0.14 Olympus 2010-09-28 rammstein4o $
 * @copyright  2007 - 2010 jVitals
 * @license   GPLv3 Open Source
 * @link       http://jvitals.com
 * @since      File available since initial release
 */

defined ('IN_AGORA') or die;

class TaskController extends AgoraPMSController
{
    function _default()
    {
		// if a recipient is not given, we display a page to select the recipients, up to 5
		// using either Name or User-Name as set in options
        $pathway = & $this->helper('pathway');
        $pathway->add(Agora::lang('PMS'),Agora::makeURL(array('task'=>'pms')));
        $pathway->add(Agora::lang('Compose'),'');
		
		$user_model = & Model::getInstance('UserModel');

        $send_to = intval(Agora::getVar("send_to"));
		$session =& JFactory::getSession();
		if (!intval(Agora::getVar('p',0))){
			$recipients = $session->get('agora_recipient', NULL , 'agora');
		}
        
		if ($send_to) { // if user selected already
            $user = $user_model->load($send_to);
            if ($user) {
				$this->view->assign('recipients',($this->agora_config['o_fullnames_enabled'] ? $user['name'] : $user['username']));
                //$this->view->assign('send_to',$user);
				$this->view->template = 'pms/send_compose';
				return;
            }
			
        } elseif (isset($recipients) && is_array($recipients)) { // check session
			$count = count($recipients);
			$recipient_list = '';
			for ($i = 0; $i < $count; $i++) {
				$user = $user_model->load($recipients[$i]);
				$recipient_list .= ($this->agora_config['o_fullnames_enabled'] ? $user['name'] : $user['username']);
				if ($i + 1 < $count ) $recipient_list .= '; ';
			}// for
			
			$this->view->assign('recipients', $recipient_list);
			$this->view->template = 'pms/send_compose';
			return;
		
		} else { // select user
			$total_users = $user_model->loadAllCount();
			$pages = ceil($total_users / 20);
			$user_model->setOrder('ORDER BY j_u.name ASC');

			$users = $user_model->loadAll('', 20, Agora::getPage($pages));
			foreach ($users as $uid_key => $user) {
				$users[$uid_key]['use_name'] = ($this->agora_config['o_fullnames_enabled'] ? $user['name'] : $user['username']);
			}
			$this->setPagination($pages);
			$Itemid = intval(Agora::getVar("Itemid"));
			
			$script_var = '
			<script type="text/javascript">
			
				var assetsBase = \''.$this->view->root_url .'/img\';
				var _LOADING_ = \''.Agora::lang('Wait').'\';
				var _Itemid_ = '. $Itemid .';
				window.addEvent(\'domready\', function() {
					updatePM()
			});
			</script>' ;
			$this->view->assign('script_var', $script_var);
			//$session =& JFactory::getSession();
			//$session->set('agora_users', null , 'agora');
			$this->view->assign('userlist', $users);
			$this->view->template = 'pms/send_select';
		}
    }
	
    function processBody($eprocess, $body, $userid, $username, $name, $sender, $useremail, $sitename, $siteurl, $title, $message){

        $eprocess->setData($body);
        $eprocess->setUserId($userid);
        $eprocess->setName($name);
        $eprocess->setUserName($username);
        $eprocess->setEmail($useremail);
        $eprocess->setSiteName($sitename);
        $eprocess->setSiteURL($siteurl);
        $eprocess->setItemId(JRequest::getVar('Itemid'));
        $eprocess->setTitle($title);
        $eprocess->setMessage($message);
        $eprocess->setPoster($sender);

        return $eprocess->Process();
		
    }

    function notification($username, $user_id, $user_email, $subject, $message, $hide_smilies, $save_message) {
	
        $config =& JFactory::getConfig();
        $mail =& JFactory::getMailer();
		$o_email_sender = trim($this->agora_config['o_email_sender']);
		if ($o_email_sender) {
			$sender_arr = explode(',', $o_email_sender);
			if (count($sender_arr) == 2) {
				$mail->setSender(array(trim($sender_arr[0]), trim($sender_arr[1])));
			} else {
				$mail->setSender($o_email_sender);
			}
		}
		
        $parser = & $this->helper('parser');
        $eprocess = & $this->helper('emailprocessor');
        $user_model = & Model::getInstance('UserModel');
        $user_fullname = $user_model->getUserFullName($username);
		$agora_user = $this->agora_config['o_fullnames_enabled'] ? $this->agora_user['name'] : $this->agora_user['username'];
		
        $parser->enable_img = 'True';
        $message = $parser->smilies($message);
        $message = $parser->links($message);
        $message = $parser->bbcode($message,0,true);
        $message = nl2br($message);

        $body = $this->processBody($eprocess, $this->agora_config['o_pm_messg'], $user_id, $username, $user_fullname, $agora_user, $user_email, $config->getValue( 'config.sitename' ), JURI::root(), $subject, $message);
        $emailSubject = $this->processBody($eprocess, $this->agora_config['o_pm_subject'], $user_id, $username, $user_fullname, $agora_user, $user_email, $config->getValue( 'config.sitename' ), JURI::root(), $subject, $message);
		
        $mail->addRecipient( $user_email );
        $mail->setSubject($emailSubject);
        $mail->setBody( $body );
        $mail->AltBody = $eprocess->getPlainData();
        $mail->IsHTML(true);
        if ($mail->Send()) { }

    }

    function editpms()
    {
        $user_model = &Model::getInstance('UserModel');        
        $sendto["username"] = Agora::getPostVar('req_username','');
        $sendto["name"] = $user_model->getUserFullName($sendto["username"]);
        
        $this->view->assign('post_body',Agora::getPostVar('req_message',''));
        $this->view->assign('post_subject',Agora::getPostVar('req_subject',''));
        $this->view->assign('edit_unsaved',1);
        $this->view->assign('send_to',$sendto);

        if (Agora::getPostVar('PMSReply')) {

            $pathway = & $this->helper('pathway');
            $pathway->add(Agora::lang('PMS'),Agora::makeURL(array('task'=>'pms')));
            $pathway->add(Agora::lang('Reply'),'');

        }
        else
        {
            $pathway = & $this->helper('pathway');
            $pathway->add(Agora::lang('PMS'),Agora::makeURL(array('task'=>'pms')));
            $pathway->add(Agora::lang('Compose'),'');
        }

        $this->view->template = 'pms/send';
    }


    function _preview()
    {
        $raw_message = Agora::getPostVar('req_message','');
        $message = $raw_message;
        $hide_smilies = Agora::getPostVar('hide_smilies',0);
        $req_username = Agora::getPostVar('req_username','');
        $show_fullname = Agora::getPostVar('show_fullname','');
        $req_subject = Agora::getPostVar('req_subject','');
        $savemessage = Agora::getPostVar('savemessage',0);

        $parser = & $this->helper('parser');

        $message = $parser->parseMessage($message,$hide_smilies);

        $post = array();
        $topic = array();

        $post['user'] = $this->agora_user;
        //Agora::prepareUser($post['user'],$this->agora_config['o_ranks']);
        $user_helper = & $this->helper('user');
        $post['user'] = $user_helper->prepareUserAvatar($post['user']);
        $post['user'] = $user_helper->prepareUserTitle($post['user']);

        $post['id'] = 0;
        $post['poster_id'] = $this->agora_user['id'];
        $post['poster'] = $this->agora_user['username'];
        $post['posted'] = time();
        $post['message'] = & $message;

        $topic['subject'] = $req_subject;

        if (Agora::getPostVar('PMSReply')) {
            $this->view->assignRef('PMSReply',Agora::getPostVar('PMSReply'));
        }

        $this->view->assignRef('post',$post);
        $this->view->assignRef('topic',$topic);

        $this->view->assign('access',array());

        $this->view->assign('req_username',$req_username);
        $this->view->assign('show_fullname',$show_fullname);
        $this->view->assign('req_subject',$req_subject);
        $this->view->assign('hide_smilies',$hide_smilies);
        $this->view->assign('savemessage',$savemessage);
        $this->view->assign('raw_message',$raw_message);

        $this->view->assign('pms_preview',true);

/*			$this->view->assign('merge',$merge);
            $this->view->assign('subscribe',$subscribe);*/

        $pathway = & $this->helper('pathway');
        $pathway->add(Agora::lang('PMS'),Agora::makeURL(array('task'=>'pms')));
        $pathway->add(Agora::lang('Preview'),'');

        $this->view->template = 'pms/preview';


    }

    function send() {
        if (Agora::getPostVar('preview')) {
            $this->_preview();
            return;
        }
        if (Agora::getPostVar('editpms')) {
            $this->editpms();
            return;
        }
		$error = false;
        $subject = Agora::getPostVar('req_subject','');
        $username = Agora::getPostVar('req_username','');
        $message = Agora::getPostVar('req_message','');
        $hide_smilies = Agora::getPostVar('hide_smilies',0);
        $save_message = Agora::getPostVar('savemessage',0);
        $user_model = & Model::getInstance('UserModel');
        $pms_model = & Model::getInstance('PMSModel');
		
		$agora_user = $this->agora_config['o_fullnames_enabled'] ? $this->agora_user['name'] : $this->agora_user['username'];
		
		$users = explode("; ", $username);

		if (isset($users) && is_array($users)) {
			foreach ($users as $uid_key => $username) {
				
				$user_id = $user_model->getUserId($username, $this->agora_config['o_fullnames_enabled'] );
        		$user_email = $user_model->getUserEmail($username, $this->agora_config['o_fullnames_enabled'] );
				if ($user_id) {
					$pms_model->sendMessage($this->agora_user['id'],$agora_user,$user_id, $username, $subject, $message, $hide_smilies, $save_message);
					$this->notification($username, $user_id, $user_email, $subject, $message, $hide_smilies, $save_message);
					unset($users[$uid_key]);
				}
				else {
					Agora::showError(Agora::lang('Invalid user-') . ' ' . $username);
					$error = true;
				}
			}
		}
		
        $session =& JFactory::getSession();
		$session->set('agora_recipient', null , 'agora');
		if ($error) {
			$this->redirect('!page');
		} else {
			$this->redirect('!page');
		}
    }
}
?>
